#ifndef A8_CJSON_H
#define A8_CJSON_H

#include <json-glib/json-glib.h>
#include <a8/xvalue.hpp>

namespace a8
{
	static void HandleJsonMember(JsonObject *obj, const gchar *key, JsonNode *val, gpointer user_data)
	{
		std::map<const gchar*, a8::XValue>& json_map = *(std::map<const gchar*, a8::XValue>*)user_data;
	
		JsonNode* node = json_object_get_member(obj, key);
		GType type = json_node_get_value_type(val);
		if (g_type_is_a(type, G_TYPE_STRING))
			{
				a8::XValue xvalue(json_node_get_string(node));
				json_map[key] = xvalue;
			}
		else if (g_type_is_a(type, G_TYPE_BOOLEAN))
			{
				a8::XValue xvalue(json_node_get_boolean(node));
				json_map[key] = xvalue;
			}
		else if (g_type_is_a(type, G_TYPE_INT64))
			{
				a8::XValue xvalue((int)json_node_get_int(node));
				json_map[key] = xvalue;
			}
		else if (g_type_is_a(type, G_TYPE_DOUBLE))
			{
				a8::XValue xvalue(json_node_get_double(node));
				json_map[key] = xvalue;
			}
		else
			{
				cout << "not support json value type, key: " << key << endl;
			}
	}

	static bool HandleJsonData2Map(const std::string& json_data, std::map<const gchar*, a8::XValue>& json_map)
	{
		JsonParser* parser = json_parser_new();
		GError* error = NULL;
		json_parser_load_from_data(parser, json_data.c_str(), json_data.size(), &error);
		if (error)
			{
				g_error_free(error);
				g_object_unref(parser);
				return false;
			}

		JsonNode* root = json_parser_get_root(parser);
		JsonObject* root_obj = json_node_get_object(root);
	
		std::map<const gchar*, a8::XValue> json_map;
		json_object_foreach_member(root_obj, HandleJsonMember, &json_map);
	
		g_object_unref(parser);
		return true;
	}
}

#endif
